package com.bite.friend.service.user.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.bite.api.RemoteJudgeService;
import com.bite.api.UserExeResult;
import com.bite.api.domain.dto.JudgeSubmitDTO;
import com.bite.api.domain.vo.UserQuestionResultVO;
import com.bite.common.core.constants.Constants;
import com.bite.common.core.domain.R;
import com.bite.common.core.enums.ProgramType;
import com.bite.common.core.enums.QuestionResType;
import com.bite.common.core.enums.ResultCode;
import com.bite.common.core.utils.ThreadLocalUtil;
import com.bite.common.security.exception.ServiceException;
import com.bite.friend.domain.question.Question;
import com.bite.friend.domain.question.QuestionCase;
import com.bite.friend.domain.question.es.QuestionES;
import com.bite.friend.domain.user.UserSubmit;
import com.bite.friend.domain.user.dto.UserSubmitDTO;
import com.bite.friend.elasticsearch.QuestionRepository;
import com.bite.friend.mapper.question.QuestionMapper;
import com.bite.friend.mapper.user.UserSubmitMapper;
import com.bite.friend.rabbit.JudgeProducer;
import com.bite.friend.service.user.IUserQuestionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserQuestionServiceImpl implements IUserQuestionService {
    @Autowired
    private QuestionRepository questionRepository;
    @Autowired
    private QuestionMapper questionMapper;
    @Autowired
    private RemoteJudgeService remoteJudgeService;
    @Autowired
    private JudgeProducer judgeProducer;
    @Autowired
    private UserSubmitMapper userSubmitMapper;
    @Override
    public R<UserQuestionResultVO> submit(UserSubmitDTO submitDTO) {
        Integer programType = submitDTO.getProgramType();
        if (ProgramType.JAVA.getValue().equals(programType))
        {
            //按照java逻辑处理
            JudgeSubmitDTO judgeSubmitDTO=assembleJudgeSubmitDTO(submitDTO);
            //这个才具备判题的功能
           return remoteJudgeService.doJudgeJavaCode(judgeSubmitDTO);
        }
            throw  new ServiceException(ResultCode.FAILED_NOT_SUPPORT_PROGRAM);
    }
//这里面已经不具备判题的功能了，如何处理?
    @Override
    public boolean rabbitSubmit(UserSubmitDTO submitDTO) {
        Integer programType = submitDTO.getProgramType();
        if (ProgramType.JAVA.getValue().equals(programType))
        {
            //按照java逻辑处理
            JudgeSubmitDTO judgeSubmitDTO=assembleJudgeSubmitDTO(submitDTO);
            //把消息发送给mq就好了，你不用去处理，消费去去处理(我们拿不到结果
            judgeProducer.produceMsg(judgeSubmitDTO);
            return true;
        }
        throw  new ServiceException(ResultCode.FAILED_NOT_SUPPORT_PROGRAM);
    }

    @Override
    public UserQuestionResultVO exeResult(Long examId, Long questionId, String currentTime) {
        Long userId=ThreadLocalUtil.get(Constants.USER_ID,Long.class);
        UserSubmit userSubmit=userSubmitMapper.selectCurrentUserSubmit(userId,examId,questionId,currentTime);
       UserQuestionResultVO resultVO=new UserQuestionResultVO();
       if(userSubmit==null){
       //判题还没有结束
           resultVO.setPass(QuestionResType.IN_JUDGE.getValue());
       }else{
           resultVO.setPass(userSubmit.getPass());
           resultVO.setExeMessage(userSubmit.getExeMessage());
           if(StrUtil.isNotEmpty(userSubmit.getCaseJudgeRes())){
               resultVO.setUserExeResultList(JSON.parseArray(userSubmit.getCaseJudgeRes(), UserExeResult.class));
           }
       }
        return resultVO;
    }

    private JudgeSubmitDTO assembleJudgeSubmitDTO(UserSubmitDTO submitDTO) {
        Long questionId=submitDTO.getQuestionId();
        QuestionES questionES=questionRepository.findById(questionId).orElse(null);
        JudgeSubmitDTO judgeSubmitDTO=new JudgeSubmitDTO();
        if(questionES!=null){
            BeanUtil.copyProperties(questionES,judgeSubmitDTO);
        }else{
            //es没找到，从数据库里面找
            Question question=questionMapper.selectById(questionId);
            BeanUtil.copyProperties(question,judgeSubmitDTO);
            //从数据库查到之后，为了防止后面接着查，我们需要把对应的数据插入到这个es里面
            questionES=new QuestionES();
            BeanUtil.copyProperties(question,questionES);
            questionRepository.save(questionES);
        }
        judgeSubmitDTO.setUserId(ThreadLocalUtil.get(Constants.USER_ID,Long.class));
        judgeSubmitDTO.setExamId(submitDTO.getExamId());
        judgeSubmitDTO.setProgramType(submitDTO.getProgramType());
        //考虑一下啊，其实es要重写一份，es之前存的字段都是空的，我们之前把index删掉，然后在重新同步一份之类的
        //或者直接我们编辑，还省事。
        judgeSubmitDTO.setUserCode(codeConnect(submitDTO.getUserCode(),questionES.getMainFuc()));
        List<QuestionCase> questionCaseList=JSONUtil.toList(questionES.getQuestionCase(), QuestionCase.class);
        List<String>inputList=questionCaseList.stream()
                .map(QuestionCase::getInput).toList();
        judgeSubmitDTO.setInputList(inputList);
        List<String>outputList=questionCaseList.stream()
                .map(QuestionCase::getOutput).toList();
        judgeSubmitDTO.setOutputList(outputList);
        return judgeSubmitDTO;
    }
    private String codeConnect(String userCode, String mainFunc) {
        String targetCharacter = "}";
        int targetLastIndex = userCode.lastIndexOf(targetCharacter);
        if (targetLastIndex != -1) {
            return userCode.substring(0, targetLastIndex) + "\n" + mainFunc + "\n" + userCode.substring(targetLastIndex);
        }
        throw new ServiceException(ResultCode.FAILED);
    }
}
